const log4js = require('../../../../utils/logUtils');
const logger = log4js.getLogger('sip');
const deviceCache = require("../../../../db/deviceCache");
const sip = require("sip");
const moment = require('moment');
const fs = require("fs");
const config = require("../../../../db/config");

const TAG = "[xmlUtils]";
module.exports = {
    toLocalPushKey(headers, callid='') {
        const toUri = sip.parseUri(headers.to.uri);
        const channelId = toUri.user;
        const camera = deviceCache.getCameraByChannelId(channelId);
        let stream = camera.deviceid + "_" + channelId;
        let pushKey;
        if (callid) {
            pushKey = stream + '_' + callid;
        }else{
            pushKey = stream;
        }
        return {pushKey, stream};
    },
    /**
     * 在推流列表里找一个拉流地址不同，但推流地址相同的
     * 即检查端口有没有已经在使用
     * @param {*} targetCamera
     * @returns
     */
    findItemInPushArray(targetCamera) {
        for (let s in deviceCache.pushArray) {
            const tempProcess = deviceCache.pushArray[s];
            if (tempProcess.rtsp_url && tempProcess.rtsp_url !== targetCamera.rtsp_url) {
                if (tempProcess.targetPort === targetCamera.targetPort && tempProcess.targetIp === targetCamera.targetIp) {
                    return tempProcess;
                }
            }
        }
        return null;
    },
    findFileByTime(startTime, endTime, pushKey) {
        // 从stream解析 deviceId_channelId
        const array = pushKey.split('_');
        const streamDirectory = array[0] + '_' + array[1];
        const path = config.record.path + '/mp4/record/proxy/';
        // 通过日期找到文件夹
        let folder = path + streamDirectory + '/' + startTime.format("YYYY-MM-DD");

        // 通过时间戳找到文件
        const files = fs.readdirSync(folder);

        let file = null;
        // 对files按时间从小到大先排序，对文件名要使用moment处理再排序
        files.sort((a, b) => {
            const aTime = moment(a.split('_')[0], 'YYYYMMDD-HHmmss');
            const bTime = moment(b.split('_')[0], 'YYYYMMDD-HHmmss');
            return aTime.isBefore(bTime) ? -1 : 1;
        });
        const startTimeSub1 = startTime.clone().subtract(1, 'seconds');
        const endTimeAdd1 = endTime.clone().add(1, 'seconds');

        files.forEach((item) => {
            // 这里文件名的格式是 年月日-时分秒
            const fileTime = moment(item.split('_')[0], 'YYYYMMDD-HHmmss');

            // 边界居然不在isBetween里面
            if (fileTime.isBetween(startTimeSub1, endTimeAdd1)) {
                file = item;
            }
        });
        let physicPath = folder + '/' + file;
        let relativePath = physicPath.replace(config.record.path + '/mp4/record/', '');
        return { physicPath, relativePath};
    }
}
